#include"SList.h"

void SLInit(SLNode** pphead)
{
	*pphead = NULL;
}

SLNode* SLBuyNode(SLDataType x)
{
	SLNode* node = (SLNode*)malloc(sizeof(SLNode));
	assert(node);
	node->data = x;
	node->next = NULL;
	return node;
}

void SLPrint(SLNode* phead)
{

	SLNode* pcur = phead;
	while (pcur!=NULL)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("NULL\n");
}

void SLPushBack(SLNode** pphead,SLDataType x)
{
	assert(pphead);
	
	SLNode* node = SLBuyNode(x);

	if (!*pphead)
	{
		*pphead = node;
		return;
	}

	SLNode* pcur = *pphead;
	while (pcur->next != NULL)
	{
		pcur = pcur->next;
	}
	pcur->next = node;

}

void SLPushFront(SLNode** pphead, SLDataType x)
{
	assert(pphead);
	SLNode* node = SLBuyNode(x);

	if (!*pphead)
	{
		*pphead = node;
		return ;
	}
	SLNode* pcur = *pphead;

	node->next = pcur;
	*pphead = node;
}

void SLPopBack(SLNode** pphead)
{
	assert(pphead && *pphead);


	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
		return ;
	}

	SLNode* pcur = *pphead;
	while (pcur->next->next!= NULL)
	{
		pcur = pcur->next;
	}
	free(pcur->next);
	pcur->next = NULL;

}

void SLPopFront(SLNode** pphead)
{
	assert(pphead && *pphead);
	SLNode* del = *pphead;

	*pphead = (*pphead)->next;
	free(del);
	del = NULL;
}
 
SLNode* SLFind(SLNode** pphead, SLDataType x)
{
	assert(pphead && *pphead);
	SLNode* pcur = *pphead;

	while (pcur)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}

	return NULL;
}

SLNode* SLFindNum(SLNode** pphead, SLDataType x)
{
	assert(pphead && *pphead);
	SLNode* p = *pphead;
	while (p)
	{
		if (p->data == x)
			return p;
		p = p->next;
	}
	return NULL;
}

void SLInsert(SLNode** pphead,SLNode* pos ,SLDataType x)
{
	assert(pphead && *pphead && pos);

	SLNode* node = SLBuyNode(x);
	if (pos == *pphead)
	{
		node->next = *pphead;
		*pphead = node;
		return;
	}

	SLNode* pret = *pphead;
	while (pret->next != pos)
	{
		pret = pret->next;
	}

	node->next = pos;
	pret->next = node;
}

void SLInsertAfter( SLNode* pos, SLDataType x)
{
	assert(pos);

	SLNode* node = SLBuyNode(x);
	
	node->next = pos->next;
	pos->next = node;
}

void SLErase(SLNode** pphead, SLNode* pos)
{
	assert(pphead && *pphead);
	assert(pos);
	SLNode* pret = *pphead;
	if (pret == pos)
	{
		SLPopFront(pphead);
		return;
	}
	while (pret->next!=pos)
	{
		pret = pret->next;
	}
	pret->next = pos->next;
	free(pos);
	pos = NULL;
}

void SLEraseAfter(SLNode** pphead,SLNode* pos)
{
	assert(pphead && *pphead);
	assert(pos);
	if (!pos->next)
	{
		return;
	}
	SLNode* cur = *pphead;
	while (pos != cur)
	{
		cur = cur->next;
	}
	SLNode* del = cur->next;
	cur->next = del->next;
	free(del);
	del = NULL;
}

void SLDesTroy(SLNode** pphead)
{
	assert(pphead);
	SLNode* pret = *pphead;


	while (*pphead)
	{
		pret = (*pphead)->next;
		free(*pphead);
		*pphead = pret;
	}
}


